package cn.snorlaxzjt.LBSserver.service;

import cn.snorlaxzjt.LBSserver.mapper.CommentMapper;
import cn.snorlaxzjt.LBSserver.po.entity.Comment;
import cn.snorlaxzjt.LBSserver.po.page.CommentPage;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CommentService {

    @Resource
    private CommentMapper commentMapper;

    public List<List<CommentPage>> queryByCommentIds(List<Long> commentIds){
        List<CommentPage> list = commentMapper.queryByCommentIds(commentIds);
        Map<Long,String> idToName = new HashMap();
        for(CommentPage m : list){
            idToName.put(m.getUserId(),m.getUsername());
        }
        list = list.stream().peek(i -> i.setReplyUsername(idToName.get(i.getReplyUserId()))).collect(Collectors.toList());
        List<List<CommentPage>> ansList = new ArrayList<>();
        while(list.size() != 0){
            List<CommentPage> finalList = list;
            List<CommentPage> curList = list.stream().filter(i->i.getMomentId().equals(finalList.get(0).getMomentId())).collect(Collectors.toList());
            ansList.add(curList);
            list = list.stream().filter(i -> !curList.contains(i)).collect(Collectors.toList());
        }
        return ansList;
    }

    public void save(Comment comment){
        commentMapper.insert(comment);
    }

    public void del(Long id){
        commentMapper.del(id);
    }

    public List<CommentPage> queryCommentByMomentId(Long id) {
        List<CommentPage> list = commentMapper.selectByMomentId(id);
        Map<Long,String> idToName = new HashMap();
        for(CommentPage m : list){
            idToName.put(m.getUserId(),m.getUsername());
        }
        list = list.stream().peek(i -> i.setReplyUsername(idToName.get(i.getReplyUserId()))).collect(Collectors.toList());
        return list;
    }
}
